<?php
/**
 * 购物车管理
 * @author cjli
 * $pro_type  0普通商品 1爆款秒杀 2圣诞节加一元 3附加商品-衬衫（衬衫清库存）
 */
class CartAction extends HomeAction
{

	public function _initialize()
	{
		parent::_initialize();
	}

	public function info()
	{
        global $user;
		$data = array(
			'docTitle' => L('meta_title_info'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'), //head头 信息
		);
		$this->assign($data);
        //圣诞节1元钱换购领结方巾活动
		$christmas_cart['pocketSquare'] = ProductModel::get_product_collection_list(C('christmas_cart_pocketSquare'));//方巾
		$christmas_cart['bowTie']       = ProductModel::get_product_collection_list(C('christmas_cart_bowTie'));//领结
        $christmas_cart['price']    = C('christmas_cart_price');//需要的价格
        $cart_pro_type = CartModel::get_cart_product_list(false, 0, 0);
        $christmas_cart['total_amount'] = $cart_pro_type['total_amount'];
        $christmas_cart['is_closd'] = false;
        $gift_money = 0;
        $productIds = array();
        foreach($cart_pro_type['productList'] as $k => $v){
        	$productIds[] = $v['pid'];
            if($v['product']['catid'] == 2121){
                $gift_money += ($v['price']*$v['qty']);//单独购买GIFT CARD不得参加圣诞加1元换购活动
            }
        }
        if($christmas_cart['total_amount'] - $gift_money <= $christmas_cart['price']){
        	CartModel::delete_cart_product_pro_type(2);
        	$christmas_cart['is_closd'] = ture;
        	$christmas_cart['neededmoney'] = $christmas_cart['price'] - $christmas_cart['total_amount'];
        }else{
        	$christmas_cart['neededmoney'] = 0;
        }
        $christmas_add_product = CartModel::get_cart_product_pro_type(2);
        $christmas_cart['add_id']    = $christmas_add_product;
        $christmas_cart['add_count'] = count($christmas_add_product);
        $this->assign('christmas_cart', $christmas_cart);
        $christmas_is_start = 1;
        if(strtotime(C('christmas_cart_startdata'))>=time() || strtotime(C('christmas_cart_enddata'))<time()){
        	$christmas_is_start = 0;
        }
        $this->assign('christmas_is_start', $christmas_is_start);
        //圣诞节1元钱换购领结方巾活动

		$cartProductList = CartModel::get_cart_product_list();
		//var_dump($cartProductList);
        //有下架的商品 移动到下架购物车表
    	foreach ($cartProductList['productList'] as $key => $cart) {
		    if(in_array($cart['product']['display'], array(0,2))){
		    	$cartFindOne = M('cart_products')->where(array('id'=>$cart['id']))->find(); 
				$cart_display_add = M('cart_products_display')->add($cartFindOne);
				if($cart_display_add){
					$delCartRes = M('cart_products')->where(array('id'=>$cart['id']))->delete();
				}
		    }
    	}
    	$cartDispaly = CartModel::get_cart_product_list(false,0,'all',0); //下架的
        //有上架的商品 移动到正式购物车表
    	foreach ($cartDispaly['productList'] as $key => $cart) {
		    if($cart['product']['display'] == 1){
		    	$cartFindOne = M('cart_products_display')->where(array('id'=>$cart['id']))->find(); 
				$cart_display_add = M('cart_products')->add($cartFindOne);
				if($cart_display_add){
					$delCartRes = M('cart_products_display')->where(array('id'=>$cart['id']))->delete();
				}
		    }
    	}   	
    	//重新读一次购物车
    	$cartProductList = CartModel::get_cart_product_list();  //上架的 
    	$this->assign('upCartCount', count($cartProductList['productList'])); //count购物车中的商家商品    
        $cartDispaly = CartModel::get_cart_product_list(false,0,'all',0); //下架的
        if($cartDispaly['productList']){ 
        	//合并下架商品到购物车顶部
        	foreach ($cartDispaly['productList'] as $key => $val) {
        		$val['is_display'] = 1;
        		$cartDispaly['productList'][$key] = $val;
        	}      	        		
        	foreach ($cartProductList['productList'] as $key => $val) {
        		$cartDispaly['productList'][] = $val;
        	}
        	$cartProductList['productList'] = $cartDispaly['productList'];
        }
        //衬衫清库存 临时代码
        $shirtCleanrList = array();
        foreach ($cartProductList['productList'] as $k => $v) {
            if($v['cid'] == 0){
            	//西服跟赠送的衬衫放一起
            	$shirtCartData = array();
	            foreach ($cartProductList['productList'] as $kk => $vv) {
	            	if($vv['cid'] == $v['id']){
	            		$shirtCartData = $vv;
                        break;
	            	}
	            }
                if($shirtCartData) {
	            	$v['get_shirt'] = true; 
	            	$shirtCleanrList[] = $v;
	            	$shirtCleanrList[] = $shirtCartData;
	            }else{
	            	$shirtCleanrList[] = $v;
	            }
            }
        }
        $cartProductList['productList'] = $shirtCleanrList;
        //给营销用的
        $yx_prodid = '[';  
        //2014-7-31 修改购物车流程 不做强制身型选择
        $custom_count = 0;//是否有定制的
        $send_days = 14;//派送时间
        $pro_type_3_num = 0;//参加衬衫活动的衬衫 没有身型的数量
        $i_chest=0;//用于标记购物车是否有羊绒衫并且身形数据是否超出标准
        $data_cart=0;//用于标记身形数据是否完整
		if($cartProductList['productList']){
			$mid = AttributeModel::get_user_measure_mid();
			foreach($cartProductList['productList'] as $key=>$cartInfo){
                $measure_info=D("user_measure")->find($cartInfo['measure_id']);
                //购物车羊绒衫身形数据限制 start
                if($cartInfo['product']["model_id"]==27){
                    //判断胸围是否在范围内
                    if($measure_info['m_status']!=10&&$measure_info['m_status']!=5&&($measure_info['chest']>C('chest_max')||$measure_info['chest']<C('chest_min'))){
                        $i_chest++;
                    }
                }
                //购物车羊绒衫身形数据限制over
                //检查购物车的商品的相关身形数据是否完整
                if($cartInfo['measure_id']>0){
                    if(C("data_".$cartInfo['product']["model_id"])&&$measure_info['m_status']!=5&&$measure_info['m_status']!=10){
                        $data=C("data_".$cartInfo['product']["model_id"]);
                        foreach ($data as $v){
                            if($measure_info[$v]==0){
                                $data_cart++;
                            }
                        }
                    }
                }//echo  $data_cart;exit;
                //身形数据是否是预约量体时候加入的  不需要Check_Measurement
                if(!isset($measure_info)||$measure_info['m_status']==10){
                    $cartProductList['productList'][$key]['no_check']=1;
                }else{
                    $cartProductList['productList'][$key]['no_check']=0;
                }
				$yx_prodid .= "'".$cartInfo['pid']."',";
				//派送时间 如果不是衬衫和配饰 则为20天
				if(!in_array($cartInfo['product']['catid'], array(2062,2067))){
					$cartInfo_parentid = CategoryModel::get_category_parentid($cartInfo['product']['catid']);
					if(!in_array($cartInfo_parentid, array(2062,2067))) $send_days = 20;
				}
                $attr = unserialize($cartInfo['attr']);
				if($cartInfo['custom_type'] == '2' && is_array($attr) ){
                    if( $cartInfo['measure_id'] < 1){
	                    if($cartInfo['pro_type'] != 3) $custom_count += 1;
	                    if($cartInfo['pro_type'] == 3) $pro_type_3_num += 1;
	                    //给个默认的身型
                        if($mid){
                            //
							if($cartInfo['is_display'] == 1)
							    $cart_db = D('cart_products_display');
						    else
						        $cart_db = D('cart_products');

							$data['measure_id'] = $mid;
							$cart_db->where('id='.$cartInfo['id'])->save($data);
							$cartProductList['productList'][$key]['measure_id'] = $mid;
							//redirect(url('measure/cart',array('cid'=>$cartInfo['id'])));
					    }
				    }
                    
                    //读取购物车中定制商品的定制信息
                    list($attributeList, $size_type) = CartModel::cart_attr_show($cartInfo['pid'], $cartInfo['attr']);
				    $cartProductList['productList'][$key]['attributeList'] = $attributeList;
				    $cartProductList['productList'][$key]['size_type']     = $size_type;
				}
			}
		}
		$this->assign('pro_type_3_num', $pro_type_3_num);
        $this->assign('i_chest', $i_chest);
        $this->assign('data_cart', $data_cart);
		//给营销用的
        $yx_prodid = trim($yx_prodid, ',').']';
        $yx_totalvalue = $cartProductList['total_amount'];
        $this->assign('yx_prodid', $yx_prodid);
        $this->assign('yx_totalvalue', $yx_totalvalue);
        $this->assign('cartInfo', $cartProductList);
		$this->assign('custom_count', $custom_count);
		$this->assign('send_days', $send_days);
         //衬衫清库存
        $match_qkc_list = array();
        if(C('match_qkc')){
            $match_qkc_pid = C('match_qkc_pid'); 
            foreach ($match_qkc_pid as $pid => $money) {
            	$productRes = ProductModel::get_product_info($pid);
            	$productRes['qkc_price'] = $money;
            	$match_qkc_list[] = $productRes;
            }
        }
        $this->assign('match_qkc_list', $match_qkc_list);

		$productListpid = CartModel::Recommend($productIds);
        $productList = ProductModel::get_product_collection_list($productListpid);
	  	$this->assign('productList', $productList);
        if(!UserModel::logged())//未登录
		{
                $login_url = url('user/login', array('src' => base64_encode(url('cart/info'))));
                $this->assign('login_url',$login_url);
		}
		//身形数据列表
		$measureList = AttributeModel::get_user_measure_list();
		$this->assign('measureList', $measureList);
		//var_dump($measureList);
       //收藏列表
		$collectList = array();
		if(UserModel::logged()){
			$collectList =  CartModel::get_cart_product_list(true);
		}
        $this->assign('collectList', $collectList);
	    if(check_wap()||$_GET['mobile']==1){
		    $this->display('cart_info_mobile');
		}else{
		    $this->display('cart_info');
		}
	}

	public function info02()
	{
		global $user;
		$cartProductList = CartModel::get_cart_product_list();
		$this->assign('cartInfo', $cartProductList);
		//收藏列表
		$collectList = array();
		if(UserModel::logged()){
			$collectList =  CartModel::get_cart_product_list(true);
		}
		$this->assign('collectList', $collectList);
		$this->display('cart_info02');
	}

	/**
	 * 提交并更新购物车商品
	 */
	public function productpost()
	{//var_dump($_REQUEST);die;
 
           
		$post = $_REQUEST;
//		$post = Array
//		(
//		    'attr' => Array(574484),
//				'pid' => 233064,
//				'qty' => 1,
//				'cart' => true,
//		);

			$pid = isset($post['pid']) ? intval($post['pid']) : 0;
			$cid = isset($post['cid']) ? intval($post['cid']) : 0;
			$qty = isset($post['qty']) ? intval($post['qty']) : 1;
			$attr = isset($post['attr']) ? $post['attr'] : null;
			$custom_type = isset($post['custom_type']) ? intval($post['custom_type']) : 0;
;
	  	if (isset($post['cart']))
	  	{
//	  	  //属性键值对
//	  	  if($attr){
//	  	  	$attr = CartModel::get_product_select_attribute($attr);
//	  	  }                                                
                            
	  	  $this->add_product_cart($pid, $qty, $attr, $is_ajax = true, $custom_type,$cid);
	  	}
	  	elseif($post['is_ajax'])
	  	{
				 $this->add_product_cart($pid, $qty, $attr, $is_ajax = true, $custom_type,$cid);
			}
			elseif (isset($post['custom']))
			{
				//定制
				if($custom_type==2){
					if( ! session('custom') ){
						$this->error(L('_ERROR_ACTION_'), url(''));
					}
					$custom = unserialize(base64_decode(session('custom')));
                                         
					if(! isset($custom[$pid]) || empty($custom[$pid]) ){
						$this->error(L('_ERROR_ACTION_'), url('product/custom', 'id='.$pid));
					}
                                       
					//$attr = array_values($custom[$pid]); 
					$attr = $custom[$pid]; 

				}
          //选尺码购物
          $msizedata = isset($post['msizedata']) ? $post['msizedata'] : NULL; 
          $msizedata = unserialize(base64_decode($msizedata));

	  	  $this->add_product_cart($pid, $qty, $attr, $is_ajax = false, $custom_type,$cid, 0, 0, $msizedata);

	  	}else{
	  		$reffer_url = $_SERVER["HTTP_REFERER"];
               
        header("Location: ".$reffer_url);
        exit;
	  	}
	}

	/**
	 * 添加到购物车
	 * @param int $pid 商品ID号
	 * @param int $qty 商品数量
	 * @param array $attr 属性
	 * @param int $custom_type 定制类型
	 */
	public function add_product_cart($pid, $qty, $attr, $is_ajax = false, $custom_type=0, $cid=0,$cart_id=0, $pro_type=0, $msizedata = NULL, $getLastID = false,$add_time=0)
	{
		global $user,$language_id;
		// if($cid>0){
		// 	CartModel::delete_cart_product($cid);
		// }

		$ajax_result = array(
			'error' => 1,
			'message' => null,
			'last_id' => null,
		);
		$back_url = $_SERVER['HTTP_REFERER'];
		$product = ProductModel::get_product_info($pid);
		if(!$product){
			$msg = L('_PRODUCT_NO_EXIST_');
			if($is_ajax){
				$ajax_result['message'] = $msg;
				return $ajax_result;
			}else{
				$this->error($msg, $back_url);
			}
		}
		//暂时取消商品库存
			//$product_stock = ProductModel::get_product_stock($pid); //商品库存
                        
                     

			if(!$product['display']) //已经下架
			{
				$msg = L('_PRODUCT_SHELVES_');
				if($is_ajax){
					$ajax_result['message'] = $msg;
					return $ajax_result;
				}else{
					$this->error($msg, $back_url);
				}
			}
			/*elseif(!$product_stock) //无库存
			{
				$msg = L('_UNDERSTOCK_');
				if($is_ajax){
					$ajax_result['message'] = $msg;
					return $ajax_result;
				}else{
					$this->error($msg, $back_url);
				}
			}*/

		//增加商品购买类型  0为正常商品 1为爆款商品(只能单件)
		if(UserModel::logged()) {
			$seckill_result = D('seckill_result')->field('id, price')->where(array('user_id'=>$user['id'], 'pid'=>$pid, 'used'=>0))->find();
			if($seckill_result){
				$pro_type = 1;
				D('seckill_result')->where(array('id'=>$seckill_result['id']))->save(array('used'=>1));
			}
		}

		//判断商品是否在购物车中
		$cartInfo = false;
		if($pro_type == 0) {
			if($cid > 0){
				$cartInfo = CartModel::get_cart_product_info_by_id($cid);
			}/*else{
                $cartInfo = CartModel::get_cart_product_info_by_pid($pid, $attr, $custom_type, $pro_type); 
			}*/
		}

		//下单的数量大于库存
		//$qty = intval($qty) ? intval($qty) : 1;
		//if($qty > $product['stock']) $qty =  $product['stock'];
                 
		//如果商品存在
		if($cartInfo)
		{
			if($cid > 0 ){
			   $qty = $cartInfo['qty'];
			}else{
			   $qty += $cartInfo['qty'];
			}
			//if(isset($product_stock) && $qty > $product_stock)
			//{
				//$qty =  $product_stock;
			//}
			//变更过数量后，价格也跟着变化
			if($cartInfo['pro_type'] == 0){
				$price = ProductModel::get_final_price($cartInfo['pid'], $qty, true, $attr, $cartInfo['custom_type']);
			}else{
				$price = $cartInfo['price'];
			}
			
			CartModel::update_cart_product_info($cartInfo['id'], $qty, $price, false, $attr);
                          
		}else{
                    
			//if(isset($product_stock) && $qty > $product_stock)
			//{
				//$qty =  $product_stock;
			//}

            if($pro_type == 1 ){
            	$price = $seckill_result['price'];  
            	$qty   = 1;
            }else if($pro_type == 2 ){
            	$price = 0.5;
            	$qty   = 1;
            }else{
            	$price = ProductModel::get_final_price($pid, $qty, true, $attr, $custom_type);
            }

                            
			$post = array(
				'pid' => $pid,
				'qty' => $qty,
				'attr' => $attr,
				'custom_type' => $custom_type,
				'pro_type' => $pro_type,
				'price' =>  $price,
                'add_time'=>$add_time
			);
                                          
			if($cart_id >0){
				$cart_info = CartModel::get_cart_product_info_by_id($cart_id);
				if($custom_type == 2){
					$post['measure_id'] = $cart_info['measure_id'];
				}
				$post['match_id'] = $pid;

				$data['match_id'] = $pid;
				$cart_db = D('cart_products');
				$cart_db->where(array('id' => $cart_id))->save($data);
			}
            //2014-7-31 修改购物车流程 给定制类型 默认给一个最新的身型数据
            if($custom_type == 2){
                $mid = AttributeModel::get_user_measure_mid();
			    $post['measure_id'] = !$mid ? 0 : $mid;
            }else{
            	$post['measure_id'] = 0;
            }
            if(!$post['measure_id']&&session('schedule_user_measure_id')){
                $post['measure_id']=session('schedule_user_measure_id');
            }
			$last_id = CartModel::insert_product_to_cart($post);
			$_SESSION['goodsInCart'] ? $_SESSION['goodsInCart']++ : $_SESSION['goodsInCart']=1;
			//选尺码购物
			if($msizedata){
				$mid = MeasureModel::add_msizedata($msizedata);
				$addMdata['measure_id'] = $mid;
				D('cart_products')->where('id='.$last_id)->save($addMdata);
			}
			//鞋子直接给mid 30
			if($product['model_id'] == 25){
				$addMdata['measure_id'] = 30;
				D('cart_products')->where('id='.$last_id)->save($addMdata);
			}			
			//记录定制统计
			$set_ipcount = array(
                       'pid' => $pid,
	                   'cartid' => $last_id,
                       );
            ProductModel::set_ipcount('add_cart',$set_ipcount);
			
			if($getLastID){
		        return $last_id;
		    }
		}
                 
		if($is_ajax){
                    
			$cartInfo = CartModel::get_cart_product_list();
			$ajax_result['error'] = 0;
			$ajax_result['message'] = L('_ORDER_SUBMIT_SUCCESS_');
			$ajax_result['last_id'] = $last_id;
			$ajax_result['result'] =  array(
				'amount' => $cartInfo['total_amount'],
				'number' => $cartInfo['total_number'],
				'weight' => $cartInfo['total_weight'],
			);
			return $ajax_result;
		}else{
			redirect(url('cart/info'));
		}

	}

	/**
	 * 删除购物车中的商品
	 */
	public function deleteproductfromcart()
	{
		$cart_id = intval($_GET['cart_id']);
		if(!$cart_id){
			redirect(url('cart/info'));
		}
		//圣诞组合产品一起删除
		$cartinfo = CartModel::get_cart_product_info_by_id($cart_id);
		if($cartinfo['pro_type']==2){
            CartModel::delete_cart_product_pro_type(2);
		}else{
			CartModel::delete_cart_product($cart_id);
		}
		
		$count = CartModel::get_cart_product_count();
		if(!$count){
			unset($_SESSION['cart']);
			$this->error(L('_CART_NOT_EMPTY_'), url(''));
		}else{
			redirect($_SERVER['HTTP_REFERER']);
		}
	}

	/**
	 * ajax更新购物车商品库存
	 */
	public function update_cart_product_ajax()
	{   
		//改成适应增加裤子
		$cart_id = $_GET['cart_id'];
		$is_pants_edit = false;
		if(is_numeric($cart_id)){
            $cart_id = intval($cart_id);
		}else{
            $pants_res = explode('_', $cart_id);
            if(isset($pants_res[1]) && $pants_res[1] == 'pants'){
                $cart_id      = intval($pants_res[0]);
                $is_pants_edit = true;
            }else{
            	echo 0;exit;
            }
		}
		$qty = intval($_GET['qty']);
		$cartInfo = CartModel::get_cart_product_info_by_id($cart_id);

		//秒杀不能增加数量
		if($cartInfo['pro_type'] > 0){
			echo 0;exit;
		}

        //暂时取消库存
		// if($cartInfo['pid']){
		// 	$product_stock = ProductModel::get_product_stock($cartInfo['pid']); //商品库存
		// }

		// if(isset($product_stock) && $qty > $product_stock)
		// {
		// 	$qty =  $product_stock;
		// }

		//变更过数量后，价格也跟着变化
		$price = ProductModel::get_final_price($cartInfo['pid'], $qty, true, $cartInfo['attr'], $cartInfo['custom_type']); 
		$affected = CartModel::update_cart_product_info($cart_id, $qty, $price, $is_pants_edit);
		echo (int) $affected;
	}

	/**
	 * ajax获取购物车商品总数
	 */
	public function get_cart_info_ajax()
	{
		$cartInfo = CartModel::get_cart_product_list();
        $gift_money = 0;
        foreach($cartInfo['productList'] as $k => $v){
            if($v['product']['catid'] == 2121){
                $gift_moeny += ($v['price']*$v['qty']);//有giftcard 使用限制
            }
        }
        
		$info = array(
			'amount' => $cartInfo['total_amount'],
			'number' => $cartInfo['total_number'],
			'weight' => $cartInfo['total_weight'],
			'dingjin' => $cartInfo['total_dingjin'],
			'amount_normal' => $cartInfo['total_amount_normal'],
            'total_gift_money' => $gift_moeny
		);
		echo json_encode($info);exit;
	}

    //优惠码 圣诞节优惠码处理
    public function christmas_coupon($coupon){
        $christmas_coupon = CartModel::christmas_coupon_code($coupon);
        if($christmas_coupon && $christmas_coupon['coupon_used'] == 0){
        	$amount = $_GET['amount'];
		    $amount -= CartModel::special_total_amount(); //减去特殊商品总金额
	    	if($christmas_coupon['prize_type'] == 5){
	            $price = CartModel::cart_type_price('2062');
	            if($price >= 60){
	                $price = ($amount - 60) <= 0 ? $amount : 60;//优惠码金额大于订单金额 处理
		            $info = array(
		            	'error' => 1, 
		            	'errStr' => '', 
		            	'price' => $price,
		            );
		            echo json_encode($info);exit;          	
	            }
	    	}else if($christmas_coupon['prize_type'] == 6){
	            $price = CartModel::cart_type_price('2061');
	            $price += CartModel::cart_type_price('2120');
	            $price += CartModel::cart_type_price('2119');
	            $price += CartModel::cart_type_price('2093');
	            $price += CartModel::cart_type_price('2104');
	            if($price >= 200){
	                $price = ($amount - 200) <= 0 ? $amount : 200;//优惠码金额大于订单金额 处理
		            $info = array(
		            	'error' => 1, 
		            	'errStr' => '', 
		            	'price' => $price,
		            );
		            echo json_encode($info);exit;          	
	            }
	    	}
        }
        $info = array(
        	'error' => 0, 
        	'errStr' => L('invalid_coupon'),
        	'price' => 0,
	    );
	    echo json_encode($info);exit;        
    }
    
    //营销活动，老用户50%优惠码
    public function staywithus(){
    	//优惠码 老用户促销
        if(strtolower($_GET['favorables']) == 'staywithus'){
         	$amount = $_GET['amount'];
		    $amount -= CartModel::special_total_amount(); //减去特殊商品总金额
		    
		    $cart = CartModel::get_cart_product_list(false, 0, 0);  
            $discountRate = 0.5; //折扣率
            $discount     = 0;   //可减免的钱数
		    foreach ($cart['productList'] as $key => $val) {
		    	//是否是老用户活动中特定的可折扣id中
		    	if(in_array($val['pid'], C('staywithus'))){
                    $discount  += $val['qty']*$val['product']['price'] * $discountRate;
		    	}
		    }
	        if($discount == 0){
				$error  = 0;
	            $price  = 0;
	            $errStr = L('invalid_coupon');
	        }else{
	            $error = 1;
	            $price = $discount;
	            $errStr='';
	        }
            $info = array(
                    'error'  => $error, 
                    'errStr' => $errStr, 
                    'price'  => $price
            );
            echo json_encode($info);exit; 
        }
    }

    //营销活动，20%优惠码
    public function slk(){
    	//优惠码 老用户促销
        if(strtoupper($_GET['favorables']) == 'SLK20OFF'){
	        $discount = 0;   //可减免的钱数        	
            //时间判断
            if(time() < strtotime(C('slk_close_time'))){      
	        	$SLKpid =  C('slk');
	         	$amount = $_GET['amount'];
			    $amount -= CartModel::special_total_amount(); //减去特殊商品总金额
			    
			    $cart = CartModel::get_cart_product_list(false, 0, 0);  
	            $discountRate = 0.2; //折扣率
	            //$discount     = 0;   //可减免的钱数
			    foreach ($cart['productList'] as $key => $val) {
			    	//是否在特定的可折扣id中
			    	if(in_array($val['pid'], $SLKpid)){
	                    $discount  += $val['qty']*$val['product']['price'] * $discountRate;
			    	}
			    }
		    }

	        if($discount == 0){
				$error  = 0;
	            $price  = 0;
	            $errStr = L('invalid_coupon');
	        }else{
	            $error = 1;
	            $price = $discount;
	            $errStr='';
	        }
	        		    
            $info = array(
                    'error'  => $error, 
                    'errStr' => $errStr, 
                    'price'  => $price
            );
            echo json_encode($info);exit; 
        }
    }
	/*
     * 优惠码
     * favorable 
     * 
     */
	public function favorable(){
		global $user,$language_id;
		$error = 1;
        $errStr = '';
        $price = 0;
        $cartlist = CartModel::get_cart_product_list(false, 0, 0);
        $amount =$cartlist['total_amount'];
        //营销活动，老用户50%优惠码
        if(time() < strtotime(C('staywithus_close_time'))){
            $this->staywithus();
        }
        
        //营销活动，20%优惠码  
        $this->slk();

        //优惠码 圣诞节优惠码处理
        if(strpos($_GET['favorables'],'Xmas') !== false){
            $this->christmas_coupon($_GET['favorables']);exit;
        }

        //优惠码为3X2SHIRTS的话 进行三件衬衫免费一件最低价的活动
        if($_GET['favorables'] == '3X2SHIRTS' || $_GET['favorables'] == '3X2SHIRT'){
            $returnInfo = CartModel::cart_shirt_free();
			if($returnInfo['num'] < 3){
				$error = 0;
				$errStr = L('AFreeShirt_errstr');//$errStr = '本单不符合三件衬衫活动';
	        }    
            $info = array(
            	'error' => $error, 
            	'errStr' => $errStr, 
            	'price' => $returnInfo['minPrice']
            );
            echo json_encode($info);exit;
        }
        //优惠套装
        if($_GET['favorables'] == 'BUNDLE1' || $_GET['favorables'] == 'BUNDLE2' || $_GET['favorables']== 'BUNDLE3' || $_GET['favorables']=='BUNDLE4' || $_GET['favorables'] == 'BUNDLE5'){
            $return = CartModel::cart_package_free($_GET['favorables']);
	        if(!$return){
				$error = 0;
				$errStr = L('package_coupon_validate');
	            $price = 0;
	        }else{
	            $error=1;
	            $price = $return['money'];
	            $errStr='';
	        }
	       // var_dump($return);die;
            $info = array(
                    'error' => $error, 
                    'errStr' => $errStr, 
                    'price' => $price
            );
               echo json_encode($info);exit; 
        }
		$amount -= CartModel::special_total_amount(); //减去特殊商品总金额
        $favorable_db = M("favorable");
		//$coupon['coupon_code'] = substr($_GET['favorables'],1);

		$where['min_amount'] = array('lt',$amount);
		$where['max_amount'] = array('gt',$amount);
		$where['coupon_code'] = $_GET['favorables'];
        $where['status'] = array('neq',0);
        $where['expiration_time'] = array('gt',time());
        $favorable_info = $favorable_db->where($where)->find();
		if($favorable_info){
			$price = $favorable_info['coupon_money'];
			if(($amount - $price) <= 0){//优惠码金额大于订单金额 处理
                $price = $amount;
            }
		}else{
			$error = 0;
			$errStr = L('invalid_coupon');
		}

        if($favorable_info['status'] == 3){//黑色星期五优惠码处理 （规定时间内无使用限制）
            if($favorable_info['start_time'] > time()){
                        $error = 0;
			$errStr = L('COUPON_START_TIME');
                        $price = 0;
            }else{
               if(($amount - $price) <= 0){//优惠码金额大于订单金额 处理
                   $price = $amount;
               }
            }
        }
        
        if($favorable_info['status'] == 4){//折扣优惠码
        	if(strtolower($_GET['favorables']) == strtolower('UniSpecial15')){
                if(!UserModel::logged() || !strstr(strtolower($user['email']), 'edu')){
                    $error = 0;
			        $errStr = L('invalid_coupon');
			        $price = 0;
			        $info = array(
			        	'error' => $error, 
			        	'errStr' => L('edu_tips'),
			        	'price' => $price
			        );
					echo json_encode($info);exit;			        
                }   
        	}
            $price = $amount - $amount * ($favorable_info['coupon_money']/100); //折扣优惠码 优惠价格字段当作折扣率用
        }
        foreach($cartlist['productList'] as $key => $val){
            if($val['product']['catid'] == 2121){//giftcard不能使用优惠码
                $error = 0;
                $errStr = L('_gift_cart_rule_'); 
                $price = 0;
                break;
            }
        }
        
        $info = array(
        	'error' => $error, 
        	'errStr' => $errStr, 
        	'price' => $price
        );
		echo json_encode($info);exit;
	}

	/**
	 * 获取用户可用红包
	 */
    public function get_bonus_list(){
    	if(UserModel::logged()){
    		$amount = $_POST['amount'];
		    $amount -= CartModel::special_total_amount(); //减去特殊商品总金额
			//减去gift_moeny
			$cartInfo = CartModel::get_cart_product_list();
            $gift_moeny = 0;
            foreach($cartInfo['productList'] as $k => $v){
                if($v['product']['catid'] == 2121){
                    $gift_moeny += ($v['price'] * $v['qty']);//有giftcard 红包使用限制
                }
            }
			$amount -= $gift_moeny;
		    if(floatval($amount) <= 0){
                echo "";exit;
		    }
			
			//看用户可以使用多少红包
			$bonusList = UserModel::get_bonus_list();
			if($bonusList){
				$bonusHtml = "";
				foreach ($bonusList as $key => $val) {
					if($amount >= $val['min_goods_amount']){
						if($val['is_share'] == 1) //////////////////////黑五临时处理  本行直接删除
	                        $bonusHtml .= '<option value="'.$val['id'].'">'.$val['type_name'].'['.currency($val['type_money']).']</option>';
				    }
				}
				echo $bonusHtml;exit;
			}
			echo "";exit;
    	}
    }

	/**
	 * 提交订单页面
	 */
	public function checkout()
	{

        global $user,$language_id;
		$data = array(
			'docTitle' => L('meta_title_checkout'),
			'docKeywords' => L('meta_keywords'),
			'docDescription' => L('meta_description'),
		);
		$this->assign($data);
		//不登录购物
		//$_POST['coupon_code'] = $_POST['coupon_code']?$_POST['coupon_code']:''; 
		$countiue_buy = intval($_GET['countiue_buy']);
		if($countiue_buy){
			session('countiue_buy', 1);
			if(isset($_GET['src'])) redirect(base64_decode($_GET['src']));
		}
		if(! UserModel::logged() && !session('countiue_buy'))
		{
			redirect(url('user/login', array('src' => base64_encode(url('cart/checkout')))));
		}
        
        //如果是合作伙伴 则跳到合作伙伴的下单页面
		if(UserModel::logged() && $user['is_partner'] == 1){
			$this->error(L('partner_no_user_checkout'), url('partner/order_add'));exit;
		}
        
        //圣诞节活动 判断 如果不符合条件自动跳回购物车页面
        if(count(CartModel::get_cart_product_pro_type(2))>0){      
	        $christmas_cart['price']    = C('christmas_cart_price');//需要的价格
	        $cart_pro_type = CartModel::get_cart_product_list(false, 0, 0);
	        $christmas_cart['total_amount'] = $cart_pro_type['total_amount'];
	        if($christmas_cart['total_amount'] < $christmas_cart['price']){
	        	//redirect(url('cart/info'));exit;
	        	CartModel::delete_cart_product_pro_type(2);
	        }
        }

		//订单信息
		$cartInfo = CartModel::get_cart_product_list();
        $amount=$cartInfo['total_amount'];
        //结算手续费用  超重费   预约量体费用
        $Payment=A("Payment");
        $plus_size_fee=$Payment->getPaymentMoney1(null,$amount);
        $this->assign('plus_size_Fee',$plus_size_fee);

		if(!isset($cartInfo['productList']) && empty($cartInfo['productList'])){
			$this->error(L('_CART_NOT_EMPTY_'), url(''));
		}
        //购物车中有下架商品，请返回修改
		foreach ($cartInfo['productList'] as $key => $cart) {
			if(in_array($cart['product']['display'], array(0,2))){
			    $this->error(L('cart_have_sold_out'), url('cart/info'));exit;
			}
		}
		foreach($cartInfo['productList'] as $key=>$value){
			$attr = unserialize($value['attr']);
			if($value['custom_type'] == '2' && is_array($attr) && $value['measure_id'] < 1){
				redirect(url('cart/info'));
			}
            $measure_info=D("user_measure")->find($value['measure_id']);
            if($value['product']["model_id"]==27){
                //获取胸围
                if($measure_info['m_status']!=5&&$measure_info['m_status']!=10&&($measure_info['chest']>C('chest_max')||$measure_info['chest']<C('chest_min'))){
                    redirect(url('cart/info'));//有羊绒衫并且身形数据超过115返回购物车
                }
            }
            //身形数据不完整
            if(C("data_".$value['product']["model_id"])&&$measure_info['m_status']!=5&&$measure_info['m_status']!=10){
                $data=C("data_".$value['product']["model_id"]);
                foreach ($data as $v){
                    if($measure_info[$v]==0){
                        redirect(url('cart/info'));
                    }
                }
            }
		}


		if(isset($_POST['dosubmit']))
		{
			//提交订单时注册
			if(isset($post['checkout_password']) && $post['checkout_password'] && isset($post['checkout_confirm_password']) && $post['checkout_confirm_password'])
			$regs_result = $this->checkout_registory($post);
			$result = (Array)json_decode($regs_result);
			if($result['error']){
				$this->error($result['message'], url('user/register'));
			}
                            $post = $_POST;
			//验证token
			if($post['ordertoken'] != OrderModel::get_order_token())
			{
				$this->error(L('_TOKEN_ERROR_'), url('cart/info'));
			}

			//如果选择已经有的地址
			if($user['id'] && $post['address_id'] && $post['is_new_address']==0){
				$addressInfo = UserModel::get_address_info($post['address_id']);
				if($addressInfo){
					$post['delivery_first_name'] = $addressInfo['delivery_first_name'];
					$post['delivery_last_name'] = $addressInfo['delivery_last_name'];
					$post['delivery_phone'] = $addressInfo['delivery_phone'];
					$post['delivery_mobile'] = $addressInfo['delivery_mobile'];
					$post['delivery_postcode'] = $addressInfo['delivery_postcode'];
					$post['delivery_email'] = $addressInfo['delivery_email'];
					$post['delivery_cid'] = $addressInfo['delivery_cid'];
					$post['delivery_pid'] = $addressInfo['delivery_pid'];
					$post['delivery_province'] = $addressInfo['delivery_province'];
					$post['delivery_city'] = $addressInfo['delivery_city'];
					$post['delivery_address'] = $addressInfo['delivery_address'];
					$post['delivery_address2'] = $addressInfo['delivery_address2'];
					$post['delivery_address3'] = $addressInfo['delivery_address3'];
					$post['delivery_time'] = $addressInfo['delivery_time'];
					$post['adelivery_address_id'] = $addressInfo['id'];
				}
			}

			$post['measure_data'] = $measure['measure_data'];

            //优惠码 圣诞节优惠码处理
	        if(strpos($post['coupon_code'],'Xmas') !== false){
	            CartModel::christmas_coupon_used($post['coupon_code']);
	        }else if(strtoupper($post['coupon_code']) == '3X2SHIRTS'){
	            $returnInfo = CartModel::cart_shirt_free();
				if($returnInfo['num'] >= 3){
                    $post['coupon_money'] = $returnInfo['minPrice'];
		        }else{
                    unset($post['coupon_money']);
                    unset($post['coupon_code']);
                    unset($post['favorable']);
		        }
	        }else if($post['coupon_code']){//更新一次性使用的优惠码信息
                    $favorable_db = new FavorableModel();
                    $favorable=$favorable_db->setinviteCouponInfo($post['coupon_code']);
                    if($favorable === 'failure'){//处理失效优惠码
                        unset($post['coupon_money']);
                        unset($post['coupon_code']);
                        unset($post['favorable']);
                    }
            }
            $post['hongbao_money']=0;
            //计算配送费用
            if(UserModel::logged()){
                $Public = A("Public");
                $area_id= $Public->getaddressinfo1($post['address_id'])['delivery_cid'];
            }else{
                $area_id=$post['delivery_cid'];
            }
            $post['payment_fee']= $plus_size_fee;
            $shipping_method =$post['shipping_method'];
            $post['shipping_fee']=$Payment->getShippingMoney1($shipping_method, intval($area_id),$amount,intval($post['goods_weight']),intval($post['goods_number']));
            $post['is_mobile']=intval(check_wap2());
            //添加到订单表
			if(!$order_id = OrderModel::insert_order($post)){
				$this->error(L('_ORDER_SUBMIT_FAILURE_'), url('cart/info'));
			}
            $product_name_str="";//商品字符串
			//添加产品到订单关联列表
			foreach ($cartInfo['productList'] as $k=>$cart){
				$set = array(
					'order_id' => $order_id,
					'product_id' => $cart['pid'],
					'product_sn' => $cart['product']['sn'],
					'product_name' => $cart['product']['name'],
					'sell_price' => $cart['product']['sell_price'],
					'qty' => $cart['qty'],
					'weight' => $cart['product']['weight'],
					'total_weight' => $cart['qty'] * $cart['product']['weight'],
					'pay_price' => $cart['product']['price'],
					'total_amount' => $cart['product']['price'],
					'custom_type' => $cart['custom_type'],
					'chima' => $cart['chima'],
					'car_type' => $cart['car_type'],
					'designer_id' => $cart['product']['designer_id'],
		  			'attr' => $cart['attr'],
					'measure_id' => $cart['measure_id'],
					'special_request_1' => $cart['special_request'],
					'pants_price' => $cart['product']['pants_price'],
					'pants_qty'   => $cart['pants_qty'],
				);
				$orderitemid = OrderModel::insert_order_items($order_id, $set);
                 //预约量体获取measure_id
                $last_measyre_id=$cart['measure_id'];
				//记录定制统计
				$set_ipcount = array(
					        'cartid'      => $cart['id'],
				            'orderid'     => $order_id,
				            'orderitemid' => $orderitemid,
	                       );
	            ProductModel::set_ipcount('add_order',$set_ipcount);
                if($k==0){
                    $product_name_str .= $cart['product']['name']."x".$cart['qty'];
                }else {
                    $product_name_str .= "," . $cart['product']['name']."x".$cart['qty'];
                }

			}
            //修改预约信息绑定的订单id
            $measure_info=MeasureModel::get_measure_one(array('id'=>$last_measyre_id));
            if($measure_info['m_status']==10){
                D("order_measure")->where(array('id'=>$measure_info['order_measure_id']))->save(array('order_id'=>$order_id));
            }
			//更新订单各种费用
			if($cartInfo['productList']['0']['chima'])
				$payment_status = OrderModel::update_order_prices02($order_id);
			else
				$payment_status = OrderModel::update_order_prices($order_id);
			//保存配送地址
			if($user['id']){
				//如果是编辑地址
				if(isset($post['adelivery_address_id']) && $post['adelivery_address_id']){
					$post['address_id'] = $post['adelivery_address_id'];
				}
				UserModel::update_user_address($user['id'], $post);
			}

			$orderInfo = OrderModel::get_order_info($order_id);
			//dump($orderInfo);exit;
			$mailInstance = new EmailModel();
           //收货地址
            $address=$orderInfo['delivery_province'].$orderInfo['delivery_city'].$orderInfo['delivery_address'].$orderInfo['delivery_address2'];
            //下单通知短信
            $ShortMessage=A("ShortMessage");
            $str_short_message='{"product_str":"'. $product_name_str.'","pay_money":"'.$orderInfo['pay_amount'].'","address":"'.$address.'","order_sn":"'.$orderInfo['order_sn'].'","days":"10-25"}';
            $short_mesg_result=true;//$ShortMessage->send_message('SMS_4910029',$orderInfo['delivery_phone'],$str_short_message);
            if($short_mesg_result){
                Log::write('下单短信，订单号'.$orderInfo['order_sn'].'，时间：'.date("Y-m-d H:i:s",time()));
            }
            //如果全部余额支付 支付成功短信
            //if($short_mesg_result&&$payment_status==OrderModel::PAY_PAYED){
                //$result2=$ShortMessage->send_message('SMS_4725607',$orderInfo['delivery_phone'],'{"order_sn":"'.$orderInfo['order_sn'].'"}');
               // if($result2){
                 //   Log::write('支付短信，订单号'.$orderInfo['order_sn'].'，全部余额支付，订单金额：'.$orderInfo['order_amount'].'，时间：'.date("Y-m-d H:i:s",time()));
               // }
            //}
            //判断是否使用优惠码  反给推荐人余额
            if($orderInfo['coupon_code']&&$orderInfo['product_amount']>=399&&$orderInfo['order_status']==OrderModel::ORDER_CONFIRMED&&$orderInfo['payment_status']==OrderModel::PAY_PAYED ) {
                UserModel::get_money_friend($orderInfo['coupon_code']);
            }
            //支付通知邮件
			/*if(floatval($orderInfo['pay_amount'])==0){
				if($orderInfo['payment_time'] == 0){
					$orders_db = D('orders');
					$data['payment_time'] = time();
					$orders_db->where("id=".$orderInfo['id'])->save($data);
				}
      			$email_template = UserModel::get_email_template_info('orderPayEmail', $orderInfo['language_id']);
				if($email_template){
					$content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
					$title = $mailInstance->replaceMail($email_template['title']);
					$mailInstance->sendMail($orderInfo['delivery_email'], $title, $content,'html','bcc');
				}
			}*/

            if($payment_status){//如果有购买giftcard 发送giftcard 充值卡 邮件
                OrderModel::gift_email($order_id,$mailInstance);//giftcard 发送邮件
                OrderModel::return_fabrics_kit($order_id,$mailInstance);//面料卡返现
            }
			//清空购物车
			CartModel::clearCart();
            //游客邮箱加入订阅
            if(isset($post['join_our_mailing']) && $post['join_our_mailing']){
				MeasureModel::add_subscriptions_info($post['delivery_email']);        	
            }
            cookie('self_cart_coupon', null);
            cookie('self_coupon', null);
            session("schedule_user_measure_id",null);
			redirect(url('cart/ordersuccee', 'oid='.$order_id));
//			$this->success(L('_ORDER_SUBMIT_SUCCESS_'), url('cart/ordersuccee', 'oid='.$order_id));
		}
		else
		{        
			$orderToken = OrderModel::get_order_token();
			$this->assign('ordertoken', $orderToken);
			$addressList = isset($user['id']) ? UserModel::get_address_list($user['id']) : null;
			$this->assign('addressList', $addressList);
			$paymentList = PaymentModel::get_payment_list();
			$this->assign('paymentList', $paymentList);
			$shippingList = ShippingModel::get_shipping_list();
			$this->assign('shippingList', $shippingList);
			
			$countryList = SiteModel::get_country_list();
			//国家列表默认列出几个国家
			$new_countryList = array(
					array('id' => 223, 'name' => 'United States'),      //美国
                    array('id' => 73,  'name' => 'France'),             //法国                   
                    array('id' => 38,  'name' => 'Canada'),             //加拿大
                    array('id' => 105, 'name' => 'Italy'),              //意大利
                    array('id' => 13,  'name' => 'Australia'),          //澳大利亚
                    array('id' => 195, 'name' => 'Spain'),              //西班牙
                    array('id' => 81,  'name' => 'Germany'),            //德国
                    array('id' => 176, 'name' => 'Russian Federation'), //俄罗斯
                    array('id' => 9999, 'name' => '------------------------------------------'),  //分隔符
			);
			for ($i=count($new_countryList)-1; $i >= 0; $i--) { 
				array_unshift($countryList, $new_countryList[$i]);
			}
			$this->assign('countryList', $countryList);

			$cartInfo = CartModel::get_cart_product_list();
            $gift_moeny = 0;
            $send_days = 14;//派送时间
            $joinShirtCleanr = false;//查看是否有参加衬衫清库存活动
            foreach($cartInfo['productList'] as $k => $v){
                if($v['product']['catid'] == 2121){
                    $gift_moeny += ($v['price'] * $v['qty']);//有giftcard 红包使用限制
                }
                //派送时间 如果不是衬衫和配饰 则为20天
				if(!in_array($cartInfo['product']['catid'], array(2062,2067))){
					$cartInfo_parentid = CategoryModel::get_category_parentid($cartInfo['product']['catid']);
					if(!in_array($cartInfo_parentid, array(2062,2067))) $send_days = 20;
				}
				//查看是否有参加衬衫清库存活动
				if($v['pro_type'] == 3 ){
                    $joinShirtCleanr = true;
				}
                //读取购物车中定制商品的定制信息
                list($attributeList, $size_type) = CartModel::cart_attr_show($v['pid'], $v['attr']);
			    $cartInfo['productList'][$k]['attributeList'] = $attributeList;
			    $cartInfo['productList'][$k]['size_type']     = $size_type;				
            }
           $cartInfo['gift_money'] = $gift_moeny;
           $this->assign('send_days', $send_days);
           $this->assign('joinShirtCleanr', $joinShirtCleanr);//查看是否有参加衬衫清库存活动
			//给营销用的
            $yx_prodid = '[';  
		    foreach($cartInfo['productList'] as $key=>$val){
			    $yx_prodid .= "'".$val['pid']."',";
		    }
	        $yx_prodid = trim($yx_prodid, ',').']';
	        $yx_totalvalue = $cartInfo['total_amount'];
	        $this->assign('yx_prodid', $yx_prodid);
	        $this->assign('yx_totalvalue', $yx_totalvalue);
            //给营销用的

			$this->assign('cartInfo', $cartInfo);
            $this->assign('email_address',$user['email']);
			//看用户可以使用多少积分支付
			$use_integral = UserModel::get_user_integral($cartInfo['total_amount']);
			if(is_array($use_integral))
				list($total_integral, $integral_money) = $use_integral;
			$this->assign('total_integral', isset($total_integral) ? $total_integral : 0);
			$this->assign('integral_money', isset($integral_money) ? $integral_money : 0);
			
			//看用户可以使用多少红包
			$bonusList = UserModel::get_bonus_list();
			if($bonusList){
				////////////////////// 黑五临时处理
				foreach ($bonusList as $key => $val) {
					if($val['is_share'] != 1)
					    unset($bonusList[$key]);
				}
				//////////////////////黑五临时处理
				$this->assign('bonusList', $bonusList);
			}

			//读出特殊商品的金额(秒杀，圣诞加一元)
			$this->assign('special_total_amount', CartModel::special_total_amount());
				
			//查看用户是否符合衬衫3减1
			if(cookie('self_coupon')){
				$self_coupon = cookie('self_coupon');
				if($self_coupon == "3X2SHIRTS"){
				    $returnInfo = CartModel::cart_shirt_free();
				    if($returnInfo['num'] < 3){
				    	$self_coupon = "";
				    } 
                }else if($self_coupon == "staywithus"){  //老用户营销活动
                	$self_coupon = "";  
                	if(time() < strtotime(C('staywithus_close_time'))){
	                	$staywithus_cart = CartModel::get_cart_product_list(false, 0, 0);
	                	if($staywithus_cart){
						    foreach ($staywithus_cart['productList'] as $key => $val) {
						    	//是否是老用户活动中特定的可折扣id中
						    	if(in_array($val['pid'], C('staywithus'))){
				                     $self_coupon = "staywithus"; break; 
						    	}
						    }
	                	}
                	}
                }else{
                    $coupon_info = M('favorable')->where("coupon_code='".$self_coupon."'")->find();
                    if(time() > $coupon_info['expiration_time'] || $cartInfo['total_amount'] < $coupon_info['min_amount']){
                        $self_coupon = "";
                    }
 /*                   if($coupon_info['status']!=2){
    	                $self_coupon = "";
                    }*/
                    
                }	
				$this->assign('self_coupon', $self_coupon);
			}
			if(!UserModel::logged()){
				$this->display('checkout_onlogin');
			}else{
				$this->display('checkout');
			}
		}
	}

	/**
	 * 提交订单页面(预售)
	 */
	public function checkout_yushou()
	{
		global $user,$language_id;

		if(! UserModel::logged())
		{
			redirect(url('user/login', array('src' => base64_encode(url('cart/checkout_yushou')))));
		}

		//订单信息
		$cartInfo = CartModel::get_cart_product_list($is_collect,$attribute_type=1);
		if(!isset($cartInfo['productList']) && empty($cartInfo['productList'])){
			$this->error(L('_CART_NOT_EMPTY_'), url(''));
		}


		//订单中有定制并且没身形数据
		if($cartInfo['is_custom']){
			$measure = cookie('measure');
			$measure =unserialize(base64_decode($measure));
			if($measure['user_id'] != $user['id']){
				redirect(url('measure/cart'));
			}
		}

		if(isset($_POST['dosubmit']))
		{
			$post = $_POST;
			//提交订单时注册
			if(isset($post['checkout_password']) && $post['checkout_password'] && isset($post['checkout_confirm_password']) && $post['checkout_confirm_password'])
			$regs_result = $this->checkout_registory($post);
			$result = (Array)json_decode($regs_result);
			if($result['error']){
				$this->error($result['message'], url('user/register'));
			}

			//验证token
			if($post['ordertoken'] != OrderModel::get_order_token())
			{
				$this->error(L('_TOKEN_ERROR_'), url('cart/info'));
			}

			//如果选择已经有的地址
			if($user['id'] && $post['address_id'] && $post['is_new_address']==0){
				$addressInfo = UserModel::get_address_info($post['address_id']);
				if($addressInfo){
					$post['delivery_first_name'] = $addressInfo['delivery_first_name'];
					$post['delivery_last_name'] = $addressInfo['delivery_last_name'];
					$post['delivery_phone'] = $addressInfo['delivery_phone'];
					$post['delivery_mobile'] = $addressInfo['delivery_mobile'];
					$post['delivery_postcode'] = $addressInfo['delivery_postcode'];
					$post['delivery_email'] = $addressInfo['delivery_email'];
					$post['delivery_cid'] = $addressInfo['delivery_cid'];
					$post['delivery_pid'] = $addressInfo['delivery_pid'];
					$post['delivery_province'] = $addressInfo['delivery_province'];
					$post['delivery_city'] = $addressInfo['delivery_city'];
					$post['delivery_address'] = $addressInfo['delivery_address'];
					$post['delivery_address2'] = $addressInfo['delivery_address2'];
					$post['delivery_address3'] = $addressInfo['delivery_address3'];
					$post['delivery_time'] = $addressInfo['delivery_time'];
					$post['adelivery_address_id'] = $addressInfo['id'];
				}
			}

			$post['measure_data'] = $measure['measure_data'];
			//添加到订单表
			if(!$order_id = OrderModel::insert_order($post)){
				$this->error(L('_ORDER_SUBMIT_FAILURE_'), url('cart/info'));
			}
//$order_id = 20;

			//添加产品到订单关联列表
			foreach ($cartInfo['productList'] as $cart){
				$set = array(
					'order_id' => $order_id,
					'product_id' => $cart['pid'],
					'product_sn' => $cart['product']['sn'],
					'product_name' => $cart['product']['name'],
					'sell_price' => $cart['product']['sell_price'],
					'qty' => $cart['qty'],
					'weight' => $cart['product']['weight'],
					'total_weight' => $cart['qty'] * $cart['product']['weight'],
					'pay_price' => $cart['product']['price'],
					'total_amount' => $cart['product']['price'] * $cart['qty'],
					'custom_type' => $cart['custom_type'],
					'chima' => $cart['chima'],
					'car_type' => $cart['car_type'],
					'designer_id' => $cart['product']['designer_id'],
		  			'attr' => $cart['attr'],
				);
				OrderModel::insert_order_items($order_id, $set);
			}
			//更新订单各种费用
			/*if($cartInfo['productList']['0']['chima'])
				OrderModel::update_order_prices02($order_id);
			else*/
			OrderModel::update_order_prices($order_id);

			//保存配送地址
			if($user['id']){
				//如果是编辑地址
				if(isset($post['adelivery_address_id']) && $post['adelivery_address_id']){
					$post['address_id'] = $post['adelivery_address_id'];
				}
				UserModel::update_user_address($user['id'], $post);
			}

			//发送下单邮件
			$orderInfo = OrderModel::get_order_info($order_id);
			$mailInstance = new EmailModel();
			$email_template = UserModel::get_email_template_info('orderTradingEmail', $orderInfo['language_id']);
			if($email_template){
				$orderInfo['productList'] = OrderModel::get_order_product_list($order_id);
				$content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
				$title = $mailInstance->replaceMail($email_template['title']);
				$mailInstance->sendMail($orderInfo['delivery_email'], $title, $content);
			}

			//支付通知邮件
			if(floatval($orderInfo['pay_amount'])==0){
      			$email_template = UserModel::get_email_template_info('orderPayEmail', $orderInfo['language_id']);
				if($email_template){
					$content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
					$title = $mailInstance->replaceMail($email_template['title']);
					$mailInstance->sendMail($orderInfo['delivery_email'], $title, $content,'html','bcc');
				}
			}

			redirect(url('cart/ordersuccee', 'oid='.$order_id));
//			$this->success(L('_ORDER_SUBMIT_SUCCESS_'), url('cart/ordersuccee', 'oid='.$order_id));
		}
		else
		{
			$orderToken = OrderModel::get_order_token();
			$this->assign('ordertoken', $orderToken);
			$addressList = isset($user['id']) ? UserModel::get_address_list($user['id']) : null;
			$this->assign('addressList', $addressList);
			$paymentList = PaymentModel::get_payment_list();
			$this->assign('paymentList', $paymentList);
			$shippingList = ShippingModel::get_shipping_list();
			$this->assign('shippingList', $shippingList);
			$countryList = SiteModel::get_country_list();
			$this->assign('countryList', $countryList);
			$cartInfo = CartModel::get_cart_product_list($is_collect,$attribute_type=1);
			$this->assign('cartInfo', $cartInfo);
			//看用户可以使用多少积分支付
			$use_integral = UserModel::get_user_integral($cartInfo['total_amount']);
			if(is_array($use_integral))
				list($total_integral, $integral_money) = $use_integral;
			$this->assign('total_integral', isset($total_integral) ? $total_integral : 0);
			$this->assign('integral_money', isset($integral_money) ? $integral_money : 0);
			//看用户可以使用多少红包
			$bonusList = UserModel::get_bonus_list();
			//dump($bonusList);
			if($bonusList)
				$this->assign('bonusList', $bonusList);
			if(!UserModel::logged()){
				$this->display('checkout_onlogin');
			}else{
				$this->display('checkout_yushou');
			}
		}
	}

	//下单成功页面
	public function ordersuccee()
	{
		global $user,$language_id;
		$order_id = intval($_GET['oid']);
		$no_pay = $_GET['no_pay'];
		$orderInfo = OrderModel::get_order_info($order_id);		
        //跳转的url
        $jumpUrl =  'order/query/order_sn/'.$orderInfo['order_sn'];
        if(UserModel::logged()){
        	if($user['is_partner'] == 1){
        		$jumpUrl = "partner";
        	}else{
                $jumpUrl = "user";
        	}
        	if($orderInfo){
        		$jumpUrl .=  '/order_info/oid/'.$orderInfo['id'];
        	}else{
        		$jumpUrl .=  '/order_list';
        	}      
        }
        $jumpUrl_js = "javascript:top.location.href='http://".$_SERVER['HTTP_HOST']."/".$jumpUrl."';"; 
        C('TMPL_ACTION_ERROR', THEMES_PATH.'public/paymentFailed.phtml'); // 变更错误提示地址   

		//有产品下架的情况下不让支付
		if(orderModel::get_order_product_isdown($order_id)){
           $this->error(L('_ORDER_PAY_PRODUCT_DOWN').' ', $jumpUrl_js, '', 5); //code 002
		}		


		//dump($orderInfo);exit;
		$orderInfo['payment'] = PaymentModel::get_payment_info($orderInfo['payment_method']);
		$this->assign('orderInfo', $orderInfo);
		//$this->assign('productList', $productList);

		//$productList = PaymentModel::getCategoryListBase();

		//获取商品名称，货号，以及单价，数量
		$order_items_db  = D('orders_items');
		$order_items_info = $order_items_db->where(array('order_id'=>$orderInfo['id']))->select();
		
		foreach($order_items_info as $key=>&$value){
			$product_db = D('product');
			$product_info = $product_db->where(array('id'=>$value['product_id']))->find();		
			$category_db= D('category_items');
			$category_info = $category_db->where(array('category_id'=>$product_info['catid'],'language_id'=>$language_id))->find();
			$value['category_name'] = $category_info['name'];

		}
		$this->assign('order_items_info',$order_items_info);

		//支付按钮
		import('COM.Payment');
		$paymentInstance = Payment::getInstance($orderInfo['payment_method']);
		
		$payOrderInfo = $orderInfo;
		$payOrderInfo['currency'] = isset($_SESSION['currency']) && $_SESSION['currency'] ? $_SESSION['currency'] : C('currency'); //币种
		$payOrderInfo['pay_amount'] = currency($orderInfo['pay_amount'],null,false);
		$paymentSubmit = NUll;
		if($orderInfo['payment_status'] != OrderModel::PAY_PAYED){
			$paymentSubmit = $paymentInstance->getSubmitForm($payOrderInfo);
			//支付按钮不存在的情况下
			if(!$paymentSubmit){        
				$this->error(L('_ORDER_PAYMENT_FAILURE_').' ', $jumpUrl_js, '', 5); //code 002
			}
	    }
		$this->assign('paymentSubmit', $paymentSubmit);
		$this->assign('payOrderInfo', $payOrderInfo);
		$this->assign('no_pay', $no_pay);
		$this->display('ordersuccee');
	}

	//支付后跳转显示结果页
	public function callback()
	{
		$order_id = intval($_GET['oid']);
		$message  = trim(urldecode($_GET['message']));
		$sign     = trim($_GET['sign']);
		$orderInfo = OrderModel::get_order_info($order_id);
		if($sign != MD5($order_id.C('pwd_key')) || !$orderInfo){
            send_http_status(404);
            $this->display(C('ERROR_PAGE'));
            exit;
		}
		$orderInfo['productList'] = OrderModel::get_order_product_list($order_id);
        
        //联盟营销代码
        $buttJoint = array();
        $buttJoint['skulist']  = '';
        $buttJoint['qlist']    = '';
        $buttJoint['amtlist']  = '';
        $buttJoint['currency'] = $orderInfo['currency']; 
		$sku_id_arr = array();
		$sku_chr_arr = array();
        foreach ($orderInfo['productList'] as $key => $val) {
			$suffix = '';
			if(in_array($val['product_id'],$sku_id_arr)){
				$sku_chr_arr[$val['product_id']] += 1;
				$suffix = '_'.chr($sku_chr_arr[$val['product_id']]);
			}else{
				$ismore = false;
				foreach ($orderInfo['productList'] as $k => $v) {
					if($k != $key){
						if($v['product_id'] == $val['product_id']){
							 $ismore = true; break;
						}
					}
				}
				if($ismore){
				   $sku_id_arr[] = $val['product_id'];
			       $sku_chr_arr[$val['product_id']] = 65;
				   $suffix = '_A';
				}
			}
        	$buttJoint['skulist'] .= ($buttJoint['skulist']) ? '|'.$val['product_id'] : $val['product_id'];
			$buttJoint['skulist'] .= $suffix;
        	$buttJoint['qlist'] .= ($buttJoint['qlist']) ? '|'.$val['qty'] : $val['qty'];
        	$pay_price = $val['pay_price'] * $val['qty'] * 100;
        	$pay_price = currency($pay_price, null, false, $buttJoint['currency']);
        	$pay_price = round($pay_price);
            $buttJoint['amtlist'] .= ($buttJoint['amtlist']) ? '|'.$pay_price : $pay_price;
        }
        if(floatval($orderInfo['hongbao_money'])>0 || floatval($orderInfo['coupon_money'])>0 || floatval($orderInfo['discount_amount'])>0){
            $buttJoint['skulist'] .= '|Discount'; 
            $buttJoint['qlist']   .= '|0'; 
            $discountPrice = (floatval($orderInfo['hongbao_money'])+floatval($orderInfo['coupon_money'])+floatval($orderInfo['discount_amount'])) * 100;
            $discountPrice = currency($discountPrice, null, false, $buttJoint['currency']);
            $discountPrice = round($discountPrice);
            $buttJoint['amtlist'] .= '|-'.$discountPrice; 
        }
        $this->assign('buttJoint', $buttJoint);

        //支付后跳转的url
        $jumpUrl = "http://".$_SERVER['HTTP_HOST'].'/order/query/order_sn/'.$orderInfo['order_sn'];
        if(UserModel::logged()){
            $jumpUrl = "http://".$_SERVER['HTTP_HOST'].'/user/order_info/oid/'.$orderInfo['id'];
        }
        $this->assign('wait', 5);
        $this->assign('jumpUrl', $jumpUrl);

		$this->assign('orderInfo', $orderInfo);
		$this->assign('message',$message);

        $this->display('checkoutcallback');
    	
    }

	//修改收藏状态
	public function change_collect_status()
	{
		$cart_id = intval($_REQUEST['cart_id']);
		if(!$cart_id){
			return false;
		}
		$is_collect = intval($_REQUEST['is_collect']);
		$cart_db = D('cart_products');
		$cart_db->where('id='.$cart_id)->save(array('is_collect' => $is_collect));
		return true;
	}

	/**
	 * ajax添加商品到购物车
	 */
	public function add_to_cart_ajax()
	{
		$attr = array();
		$post =(array)json_decode(str_replace('\\','',$_POST['post']));
		$result =  $this->add_product_cart($post['pid'], $post['qty'], $post['attr'], true,$post['custom_type']);
		echo json_encode($result);
	}

	/**
	 * ajax添加商品到购物车（预售）
	 */
	public function add_to_cart_ajax02()
	{
		$attr = array();
		$post =(array)json_decode($_POST['post']);
		$result =  $this->add_product_cart02($post['pid'], $post['qty'], $post['chima'], true);
		echo json_encode($result);
	}

	/**
	 * 添加到购物车（预售）
	 * @param int $pid 商品ID号
	 * @param int $qty 商品数量
	 * @param array $attr 属性
	 */
	public function add_product_cart02($pid, $qty, $chima, $is_ajax = false)
	{
		exit;
		global $user;
		$ajax_result = array(
			'error' => 1,
			'message' => null,
		);
		$back_url = $_SERVER['HTTP_REFERER'];
		$product = ProductModel::get_product_info($pid);
		if(!$product){
			$msg = L('_PRODUCT_NO_EXIST_');
			if($is_ajax){
				$ajax_result['message'] = $msg;
				return $ajax_result;
			}else{
				$this->error($msg, $back_url);
			}
		}
		//暂时取消商品库存
			//$product_stock = ProductModel::get_product_stock($pid); //商品库存

			if(!$product['display']) //已经下架
			{
				$msg = L('_PRODUCT_SHELVES_');
				if($is_ajax){
					$ajax_result['message'] = $msg;
					return $ajax_result;
				}else{
					$this->error($msg, $back_url);
				}
			}
			/*elseif(!$product_stock) //无库存
			{
				$msg = L('_UNDERSTOCK_');
				if($is_ajax){
					$ajax_result['message'] = $msg;
					return $ajax_result;
				}else{
					$this->error($msg, $back_url);
				}
			}*/

		//判断商品是否在购物车中
		$cartInfo = CartModel::get_cart_product_yushou_pid($pid, $chima);
		//下单的数量大于库存
		//$qty = intval($qty) ? intval($qty) : 1;
		//if($qty > $product['stock']) $qty =  $product['stock'];

		//如果商品存在
		if($cartInfo)
		{
			$qty = $qty + $cartInfo['qty'];
			//if(isset($product_stock) && $qty > $product_stock)
			//{
				//$qty =  $product_stock;
			//}
			CartModel::update_cart_product_info($cartInfo['id'], $qty);
		}else{

			if($user['id']){
				$cart_db = D('cart_products');
				$cart_db->where('user_id='.$user['id'].' AND car_type = 1')->delete();
			}else{
				$cart_db = D('cart_products');
				$cart_db->where('sid="'.$user['sid'].'" AND car_type = 1')->delete();
			}


			//if(isset($product_stock) && $qty > $product_stock)
			//{
				//$qty =  $product_stock;
			//}
			$post = array(
				'pid' => $pid,
				'qty' => $qty,
				'chima' => $chima,
				'custom_type' => $product['attribute_type'],
				'car_type' => 1,
			);
			CartModel::insert_product_to_cart($post);
			//$_SESSION['goodsInCart'] ? $_SESSION['goodsInCart']++ : $_SESSION['goodsInCart']=1;
		}
		if($is_ajax){
			$cartInfo = CartModel::get_cart_product_list($is_collect);
			$ajax_result['error'] = 0;
			$ajax_result['message'] = L('_ORDER_SUBMIT_SUCCESS_');
			$ajax_result['result'] =  array(
				'amount' => $cartInfo['total_amount'],
				'number' => $cartInfo['total_number'],
				'weight' => $cartInfo['total_weight'],
			);
			return $ajax_result;
		}else{
			redirect(url('cart/info'));
		}

	}

	/**
	 * 获取地址信息
	 */
	public function get_address_info_ajax()
	{
		$result = array(
			'error' => 1,
			'message' => null,
		);
		if(! UserModel::logged()){
			$result['message'] = L('_ILLEGAL_OPERATION_');
		}else{
			$aid = intval($_REQUEST['aid']);
			$addressInfo = UserModel::get_address_info($aid);
			if(!$addressInfo){
				$result['message'] = L('_ILLEGAL_OPERATION_');
			}else{
				$result['error'] = '0';
				$result['message'] = $addressInfo;
			}
		}
		echo json_encode($result);
	}

	/**
	 * 提交订单时注册
	 * @param array $post
	 * @return json
	 */
	public function checkout_registory($post)
	{
		$result = array(
			'error' => 1,
			'message' => '',
		);
		$post['email'] = $post['delivery_email'];
		$post['password'] = $post['checkout_password'];
		$post['confirm_password'] = $post['checkout_confirm_password'];
		$post['first_name'] = $post['delivery_first_name'];
		$post['last_name'] = $post['delivery_last_name'];

		import('COM.Validate');
		if(empty($post['email']) || !Validate::email($post['email'])){
				$result['message'] = L('_EMAIL_FORMAT_ERROR_');
			}
		elseif(empty($post['password']) || (! Validate::len($post['password'],6,20))){
				$result['message'] =  L('_THE_PASSWORD_SHOULD_BE_BETWEEN_6_20_');
			}
		elseif($post['confirm_password'] != $post['password']){
				$result['message'] =  L('_ENTER_THE_PASSWORD_TWICE_INCONSISTENT_');
			}
		elseif(UserModel::validate_email_only($post['email'])){
				$result['message'] =  L('_EMAIL_ALREADY_EXISTS_');
			}
			elseif(!$user_id = UserModel::insert_user($post)){
				$result['message'] = L('_REGISTRATION_FAILED_');
			}
			else{
				session('user_id', $user_id);
				$result['message'] = L('_LOGINED_SUCCESS_');
				$result['error'] = 0;
			}
		return json_encode($result);
	}

	//添加编辑配送地址
	public function cart_address_edit()
	{
		global $user;

		if(! UserModel::logged())
		{
			redirect(url('user/login', array('src' => base64_encode(url('cart/checkout_yushou')))));
		}

		if($_POST['dosubmit']){
				if(UserModel::update_user_address($user['id'], $_POST)){
					$this->success(L('_OPERATION_SUCCESS_'), url('cart/checkout'));
				}else{
					$this->error(L('_OPERATION_FAIL_'));
				}
		}
	}

	/**
	 * ajax添加商品到购物车
	 */
	public function add_cart_ajax()
	{
		$attr = array();
		$post =$_POST;
		$result =  $this->add_product_cart($post['pid'], $post['qty'], $post['attr'], true,$post['custom_type'],$cid,$post['cart_id']);
		echo json_encode($result);
	}

	/**
	 * 删除购物车中的商品
	 */
	public function delete_cart_ajax()
	{
		$cart_id = intval($_REQUEST['cart_id']);
		if($cart_id){
			CartModel::delete_cart_product($cart_id);
			$result = array(
				'error' => 1,
				'message' => L('_OPERATION_SUCCESS_'),
			);
		}else{
			$result = array(
				'error' => 0,
				'message' => L('_OPERATION_FAIL_'),
			);
		}
		echo json_encode($result);
	}

	public function fabricsAdd(){
		global $user;
		$post = $_POST;
		//如果面料卡数据为空，则返回页面
		if(!isset($post['customization']) || !$post['customization']){
			$this->error(L('_ERROR_ACTION_'), url('Customization/fabrics_kit'));
			exit;
		}
		$product_db = D('product');
		$productinfo = $product_db->where(array('model_id'=>19))->find();
		$this->add_product_cart($productinfo['id'], 1, serialize ($post['customization']), false,'0');				
	}

	/**
	 * ajax添加商品到购物车 圣诞
	 */
	public function add_to_cart_ajax_christmas()
	{
		$attr = array();
		$post =(array)json_decode(str_replace('\\','',$_POST['post']));
		if(is_array($post['pid'])){
			$sd_product = array_merge(C('christmas_cart_pocketSquare'),C('christmas_cart_bowTie'));
			foreach($post['pid'] as $val){
				if(!in_array($val, $sd_product)){
					$result = array(
						'error' => 1,
						'message' => 'You are too naughty!',
						'last_id' => null,
					);
					echo json_encode($result);exit;
				}
		    }
			foreach($post['pid'] as $val){
				if(count(CartModel::get_cart_product_pro_type(2))<2){
				    $result =  $this->add_product_cart($val, 1, $post['attr'], true,$post['custom_type'], 0, 0, 2);
				}else{
					break;
				}
			}
		}
		echo json_encode($result);
	}


	/**
	 * 删除购物车中的商品
	 */
	public function deleteproductfromcart_partner()
	{
		$cart_id = intval($_GET['cart_id']);
		CartModel::delete_cart_product_partner($cart_id);
	}

	/**
	 * 提交并更新购物车商品
	 */
	public function productpost_partner()
	{ 
		$post = $_REQUEST;
		$pid = isset($post['pid']) ? intval($post['pid']) : 0;
		$cid = isset($post['cid']) ? intval($post['cid']) : 0;
		$qty = isset($post['qty']) ? intval($post['qty']) : 1;
		$attr = isset($post['attr']) ? $post['attr'] : null;
		$custom_type = isset($post['custom_type']) ? intval($post['custom_type']) : 0;
        
        
		$product = ProductModel::get_product_info($pid);
		if(!$product){
			$msg = L('_PRODUCT_NO_EXIST_');
		    echo $ajax_result['message'] = $msg;
		    exit;
		}
        //根据产品类型查出  --选尺码购物
		$size_type_arr = C('m_data');
		$size_type = $size_type_arr[$product['model_id']];

        if($product['attribute_type'] !=1){
            $custom = unserialize(base64_decode(session('custom')));
			$special_request = $custom['special_request_'.$pid];
            if($custom[$pid]){
                $attr = $custom[$pid];
            }
            $custom_type = 2;
        }
        //选尺码购物
		$msizedata = array();
		foreach ($size_type as $val) {
		    $get_msizedata = $this->_request('m'.$val);
		    if(!$get_msizedata){
		    	$msizedata = NULL;
		    	break;
		    }
		    $msizedata[$val] = $get_msizedata;
		}
        if($msizedata){
            $msizedata = base64_encode(serialize($msizedata));
        }else{
            $msizedata=false;
        }
		/*if($msizedata && $cid == 0) {
            //读取定制商品的定制信息,同时放入缓存
            list($attributeList, $size_type, $attrOptionArr) = CartModel::cart_attr_show($pid, $attrData, true);			
		}*/
		if($cid > 0){$qty = 0;}
        $this->add_product_cart_partner($pid, $qty, $attr, true, $custom_type,$cid, 0, 0, $msizedata,$special_request);

	}

	/**
	 * 添加到购物车
	 * @param int $pid 商品ID号
	 * @param int $qty 商品数量
	 * @param array $attr 属性
	 * @param int $custom_type 定制类型
	 */
	public function add_product_cart_partner($pid, $qty, $attr, $is_ajax = false, $custom_type=0, $cid=0,$cart_id=0, $pro_type=0, $msizedata=false,$special_request="")
	{
		global $user,$language_id;
		// if($cid>0){
		// 	CartModel::delete_cart_product_partner($cid);
		// }

		$ajax_result = array(
			'error' => 1,
			'message' => null,
			'last_id' => null,
		);
		$back_url = $_SERVER['HTTP_REFERER'];
		$product = ProductModel::get_product_info($pid);
		if(!$product){
			$msg = L('_PRODUCT_NO_EXIST_');
			if($is_ajax){
				$ajax_result['message'] = $msg;
				return $ajax_result;
			}else{
				$this->error($msg, $back_url);
			}
		}
		//暂时取消商品库存
		//$product_stock = ProductModel::get_product_stock($pid); //商品库存
                    
		if(!$product['display']) //已经下架
		{
			$msg = L('_PRODUCT_SHELVES_');
			if($is_ajax){
				$ajax_result['message'] = $msg;
				return $ajax_result;
			}else{
				$this->error($msg, $back_url);
			}
		}
		/*elseif(!$product_stock) //无库存
		{
			$msg = L('_UNDERSTOCK_');
			if($is_ajax){
				$ajax_result['message'] = $msg;
				return $ajax_result;
			}else{
				$this->error($msg, $back_url);
			}
		}*/

		//判断商品是否在购物车中
		$cartInfo = false;
		if($pro_type == 0) {
			if($cid > 0){
				$cartInfo = CartModel::get_cart_product_info_by_id_partner($cid);
			}/*else{
                $cartInfo = CartModel::get_cart_product_info_by_pid_partner($pid, $attr, $custom_type, $pro_type); 
			}*/
		}

		//下单的数量大于库存
		//$qty = intval($qty) ? intval($qty) : 1;
		//if($qty > $product['stock']) $qty =  $product['stock'];      
		//如果商品存在
		if($cartInfo)
		{
			$qty = $qty + $cartInfo['qty'];
			//if(isset($product_stock) && $qty > $product_stock)
			//{
				//$qty =  $product_stock;
			//}
			if (!$attr) {
				$attr = $cartInfo['attr'];
			}
			//变更过数量后，价格也跟着变化
			$price = ProductModel::get_final_price($cartInfo['pid'], $qty, true, $attr, $cartInfo['custom_type']);

			CartModel::update_cart_product_info_partner($cartInfo['id'], $qty, $price, false, $attr,$special_request);
 			//选尺码购物
			if($msizedata && $cartInfo['measure_id']){
				$mid = MeasureModel::add_msizedata($msizedata,$cartInfo['measure_id']);
			}                         
		}else{
                    
			//if(isset($product_stock) && $qty > $product_stock)
			//{
				//$qty =  $product_stock;
			//}

            if($pro_type == 1 ){
            	$price = $seckill_result['price'];  
            	$qty   = 1;
            }else if($pro_type == 2 ){
            	$price = 0.5;
            	$qty   = 1;
            }else{
            	$price = ProductModel::get_final_price($pid, $qty, true, $attr, $custom_type);
            }

                            
			$post = array(
				'pid' => $pid,
				'qty' => $qty,
				'attr' => $attr,
				'special_request_1' => $special_request,
				'custom_type' => $custom_type,
				'pro_type' => $pro_type,
				'price' =>  $price,
			);
                                          
			if($cart_id >0){
				$cart_info = CartModel::get_cart_product_info_by_id_partner($cart_id);
				if($custom_type == 2){
					$post['measure_id'] = $cart_info['measure_id'];
				}
				$post['match_id'] = $pid;

				$data['match_id'] = $pid;
				$cart_db = D('cart_products_partner');
				$cart_db->where(array('id' => $cart_id))->save($data);
			}

            $post['measure_id'] = 0;
			//选尺码购物
			if($msizedata){
				$mid = MeasureModel::add_msizedata($msizedata);
				$post['measure_id'] = $mid;
                //读取定制商品的定制信息,同时放入缓存
                $attrData="";
                $pid=$post['pid'];
                list($attributeList, $size_type, $attrOptionArr) = CartModel::cart_attr_show($pid, $attrData, true);
                $custom = unserialize(base64_decode(session('custom')));
                if($custom[$pid]){
                    $post['attr'] = $custom[$pid];
                }
			}
			$last_id = CartModel::insert_product_to_cart_partner($post);
			$_SESSION['goodsInCart'] ? $_SESSION['goodsInCart']++ : $_SESSION['goodsInCart']=1;
			
			//记录定制统计
			$set_ipcount = array(
                       'pid' => $pid,
	                   'cartid' => $last_id,
                       );
            ProductModel::set_ipcount('add_cart',$set_ipcount);
		}

		if($is_ajax){
                    
			$cartInfo = CartModel::get_cart_product_list_partner();
			$ajax_result['error'] = 0;
			$ajax_result['message'] = L('_ORDER_SUBMIT_SUCCESS_');
			$ajax_result['last_id'] = $last_id;
			$ajax_result['result'] =  array(
				'amount' => $cartInfo['total_amount'],
				'number' => $cartInfo['total_number'],
				'weight' => $cartInfo['total_weight'],
			);
			return $ajax_result;
		}else{
			redirect(url('cart/info'));
		}

	}

	/**
	 * ajax更新购物车商品库存
	 */
	public function update_cart_product_ajax_partner()
	{   
		//改成适应增加裤子
		$cart_id = $_GET['cart_id'];
		$is_pants_edit = false;
		if(is_numeric($cart_id)){
            $cart_id = intval($cart_id);
		}else{
            $pants_res = explode('_', $cart_id);
            if(isset($pants_res[1]) && $pants_res[1] == 'pants'){
                $cart_id      = intval($pants_res[0]);
                $is_pants_edit = true;
            }else{
            	echo 0;exit;
            }
		}
		$qty = intval($_GET['qty']);
		$cartInfo = CartModel::get_cart_product_info_by_id_partner($cart_id);

		//秒杀不能增加数量
		if($cartInfo['pro_type'] > 0){
			echo 0;exit;
		}

        //暂时取消库存
		// if($cartInfo['pid']){
		// 	$product_stock = ProductModel::get_product_stock($cartInfo['pid']); //商品库存
		// }

		// if(isset($product_stock) && $qty > $product_stock)
		// {
		// 	$qty =  $product_stock;
		// }

		//变更过数量后，价格也跟着变化
		$price = ProductModel::get_final_price($cartInfo['pid'], $qty, true, $cartInfo['attr'], $cartInfo['custom_type']); 
		$affected = CartModel::update_cart_product_info_partner($cart_id, $qty, $price, $is_pants_edit);
		echo (int) $affected;
	}

	function checkout_partner(){

        global $user,$language_id;
        $Payment=A("Payment");
		//订单信息
		$cartInfo = CartModel::get_cart_product_list_partner();
        $amount=$cartInfo['total_amount'];
		if(!isset($cartInfo['productList']) && empty($cartInfo['productList'])){
			$this->error(L('_CART_NOT_EMPTY_'), url('partner/order_add'));
		}

        $post = $_POST;
        if(!isset($_POST['dosubmit']))
		{
			$this->error(L('_CART_NOT_EMPTY_'), url('partner/order_add'));
		}
		// echo "<pre />";
		// print_r($post);
		// exit;
		//如果选择已经有的地址,没有的话则保存地址
		$measure_id = 0;
		if($user['id'] && $post['address_id']){
           $address_id = $post['address_id'];
           $measure = MeasureModel::get_measure_one(array('address_id'=>$address_id));
           $measure_id = $measure['id'];
		}else{
			if($address_id = UserModel::update_user_address($user['id'], $post)){
				$post['address_id'] = $address_id;
				$post['measure_name'] = $post['delivery_first_name'].' '.$post['delivery_last_name'];
				$measure_id = MeasureModel::add_measure_data($post);
				//自动把合作伙伴下面的客户新增成网站会员
				UserModel::partner_user_add($address_id);				
			}
		}
			// echo "<pre />";
		// print_r($post);
		// exit;	
		$addressInfo = UserModel::get_address_info($post['address_id']);
		if($addressInfo){
			$post['delivery_first_name'] = $addressInfo['delivery_first_name'];
			$post['delivery_last_name'] = $addressInfo['delivery_last_name'];
			$post['delivery_phone'] = $addressInfo['delivery_phone'];
			$post['delivery_mobile'] = $addressInfo['delivery_mobile'];
			$post['delivery_postcode'] = $addressInfo['delivery_postcode'];
			//$post['delivery_email'] = $addressInfo['delivery_email'];
			$post['delivery_email'] = $user['email'];
			$post['delivery_cid'] = $addressInfo['delivery_cid'];
			$post['delivery_pid'] = $addressInfo['delivery_pid'];
			$post['delivery_province'] = $addressInfo['delivery_province'];
			$post['delivery_city'] = $addressInfo['delivery_city'];
			$post['delivery_address'] = $addressInfo['delivery_address'];
			$post['delivery_address2'] = $addressInfo['delivery_address2'];
			$post['delivery_address3'] = $addressInfo['delivery_address3'];
			$post['delivery_time'] = $addressInfo['delivery_time'];
			$post['adelivery_address_id'] = $addressInfo['id'];
		}
		//$post['measure_data'] = $measure['measure_data'];
        
        //把折扣金额放入红包字段 结算
        $discount = UserModel::get_rank_discount($user['rank_id']);
        $post['hongbao_money'] = $cartInfo['total_amount'] * (1-$discount);
        //购买羊绒衫胸围限制
        foreach ($cartInfo['productList'] as $cart){
            if($cart['product']['model_id'] == 27){
                $measure_id=$cart['measure_id']?$cart['measure_id']:$measure_id;
                $chest=D("user_measure")->find($measure_id);
                if($chest['chest']>C('chest_max')||$chest['chest']<C('chest_min')){
                    $this->error(L('_Cashmere_Sweaters_115_'), url('partner/order_add'));
                }
            }
        }
        $post['is_mobile']=intval(check_wap2());
        //支付费用 (超重费用，定制选项附加费用计入 折扣)
        $measure=D("user_measure")->find($measure_id);
        $post['payment_fee']=$Payment->getPaymentMoney1($post['payment_method'],$amount,1,0);
        //$post['payment_fee']=0;
        $post['hongbao_money'] += $post['payment_fee'] * (1-$discount);
        //添加到订单表
		if(!$order_id = OrderModel::insert_order($post)){
			$this->error(L('_ORDER_SUBMIT_FAILURE_'), url('partner/order_add'));
		}
        $product_name_str="";
		//添加产品到订单关联列表
		foreach ($cartInfo['productList'] as $k=>$cart){
			//鞋子不需要身型id
            if($cart['product']['model_id'] != 25){
			    $cart['measure_id'] = $cart['custom_type'] == 2 ? ($cart['measure_id'] ? $cart['measure_id'] : $measure_id) : 0;
            }else{
            	$cart['measure_id'] = 0;
            }  
			$set = array(
				'order_id' => $order_id,
				'product_id' => $cart['pid'],
				'product_sn' => $cart['product']['sn'],
				'product_name' => $cart['product']['name'],
				'sell_price' => $cart['product']['sell_price'],
				'qty' => $cart['qty'],
				'weight' => $cart['product']['weight'],
				'total_weight' => $cart['qty'] * $cart['product']['weight'],
				'pay_price' => $cart['product']['price'],
				'total_amount' => $cart['product']['price'],
				'custom_type' => $cart['custom_type'],
				'chima' => $cart['chima'],
				'car_type' => $cart['car_type'],
				'designer_id' => $cart['product']['designer_id'],
	  			'attr' => $cart['attr'],
				'special_request_1' => $cart['special_request_1'],
				'measure_id' => $cart['measure_id'],
				'pants_price' => $cart['product']['pants_price'],					
				'pants_qty'   => $cart['pants_qty'],
			);
			$orderitemid = OrderModel::insert_order_items($order_id, $set);


			//[zg ]  成衣尺寸前台录入
			$size_measure = $_POST['size_measure'];   //需要入成衣尺码表
			//商品类型
			$orderfigure = OrderModel::orderPrintFigure($orderitemid);

			//合体 修身
			$model = preg_match('/:修身 /', $orderfigure['attr']) ? 2 : 1;

			//取此身型原先有得数据

			/*
			$size_measure_data = D('size_measure')
				->field('data,time')
				->where(array('measure_id' => $cart['measure_id']))
				->find();
			$size_measure = unserialize($size_measure_data['data']);
			*/

			if (!$size_measure && $measure['m_status'] == 5) {
				$msizedata = unserialize($measure['measure_data']);
				foreach ($msizedata as $key => $val) {
					$size_data_notm_res = M('size_data_notm')->field('size_name_id,size_cm')
						->where(array('size' => $val, 'size_type' => $key))->select();
					$notm_arr = array();
					foreach ($size_data_notm_res as $notmval) {
						$notm_arr[$notmval['size_name_id']] = $notmval['size_cm'];
					}
					$size_measure[$key] = array(
						'model' => $model == 1 ? '合体' : '修身',
						'chima' => '',
						'cy' => $notm_arr,
						'mtm' => $notm_arr,
						'mtmadd' => '',
					);
				}

				$this->assign('is_xcm', 1);
			}


			$size_type = C('size_type');
			foreach ($size_type as $key => $val) {
				$eidt_array[] = NULL; //修改数据的样式数组
				$eidt_array[] = 'timeData'; //修改数据的样式数组
				$eidt_array[] = 'button'; //修改数据的样式数组

				$size_name = D('size_name')
					->where(array('size_type' => $val['id'], 'display' => 0))
					->order('sort asc')
					->select();

				$size_type[$key]['size_name'] = $size_name;

				//取MTM变更数据
				if ($size_measure[$val['id']]['mtmadd']) {
					$size_type[$key]['mtmselect'] = $size_measure[$val['id']]['mtmadd'];
				}
				foreach($size_type[$key]['mtmselect'] as $v){
					$mtmadd_k[$val['id']][]='';
					$mtmadd_v[$val['id']][]='';
				}

			}

			//处理MTM变更的数据
			foreach ($mtmadd_k as $key => $val) {
				$size_measure[$key]['mtmadd'] = array();
				foreach ($val as $k => $v) {
					if (!empty($v)) {
						$size_measure[$key]['mtmadd'][$v] = $mtmadd_v[$key][$k];
					}
				}
			}
			$measure_id = $cart['measure_id'];
			//保存默认数据
			OrderModel::set_size_measure($measure_id, 0, $size_measure);

			OrderModel::set_size_measure(0, $orderitemid, $size_measure);



			/* if($k==0){
                 $product_name_str .= $cart['product']['name']."x".$cart['qty'];
             }else {
                 $product_name_str .= "," . $cart['product']['name']."x".$cart['qty'];
             }*/
		}
		//更新订单各种费用
		if($cartInfo['productList']['0']['chima'])
			$payment_status = OrderModel::update_order_prices02($order_id);
		else
			$payment_status = OrderModel::update_order_prices($order_id);
        $orderInfo = OrderModel::get_order_info($order_id);
        //收货地址
        $address=$orderInfo['delivery_province'].$orderInfo['delivery_city'].$orderInfo['delivery_address'].$orderInfo['delivery_address2'];
      /*  //下单通知短信
        $ShortMessage=A("ShortMessage");
        $str_short_message='{"product_str":"'. $product_name_str.'","pay_money":"'.$orderInfo['pay_amount'].'","address":"'.$address.'","order_sn":"'.$orderInfo['order_sn'].'"}';
        $result=$ShortMessage->send_message('SMS_4720762',$orderInfo['delivery_phone'],$str_short_message);*/


		/*//支付通知邮件
		if(floatval($orderInfo['pay_amount'])==0){
			if($orderInfo['payment_time'] == 0){
				$orders_db = D('orders');
				$data['payment_time'] = time();
				$orders_db->where("id=".$orderInfo['id'])->save($data);
			}
  			$email_template = UserModel::get_email_template_info('orderPayEmail', $orderInfo['language_id']);
			if($email_template){
				$content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
				$title = $mailInstance->replaceMail($email_template['title']);
				$mailInstance->sendMail($orderInfo['delivery_email'], $title, $content,'html','bcc');
			}
		}*/

		//清空购物车
		CartModel::clearCart(null,'cart_products_partner');
        //跳转到订单成功页面
		if(isset($post['no_pay']) && $post['no_pay']==1){
			redirect(url('cart/ordersuccee', 'oid='.$order_id.'&no_pay=1'));
		}else{
			redirect(url('cart/ordersuccee', 'oid='.$order_id));
		}

	}

	/**
	 * ajax添加商品到购物车 衬衫清库存
	 */
	public function add_to_cart_shirt_cleanr()
	{
		$post = $_POST;

        if(C('match_qkc')){
        	$pid = $post['pid'];
        	$cid = $post['cid'];
            $match_qkc_pid = C('match_qkc_pid');
            //此条购物车数据是否已经参加过
            $count = D('cart_products')->where(array('cid'=>$cid))->count();
            if(isset($match_qkc_pid[$pid]) && $cid>0 && $count==0){
            	//生成定制缓存
                CartModel::cart_attr_show($pid, '', true);
                $custom = unserialize(base64_decode(session('custom')));
				if(isset($custom[$pid]) && !empty($custom[$pid])){
					$last_id =  $this->add_product_cart($pid, 1, $custom[$pid], true, 2, 0, 0, 3, NULL, true);
					if($last_id){
						 //$cartInfo = CartModel::get_cart_product_info_by_id($cid);
						 $editData = array(
						 	'cid'   => $cid,
						 	'price' => $match_qkc_pid[$pid],
						 	//'measure_id' => $cartInfo['measure_id'],
						 	);
						 $res = D('cart_products')->where(array('id'=>$last_id))->save($editData);
						 if($res){
							$result = array(
								'error' => 0,
								'message' => '',
								'last_id' => null,
							);
							echo json_encode($result);exit;
						}
					}					
				}        	 
            }
        }

		$result = array(
			'error' => 1,
			'message' => L('_OPERATION_FAIL_'),
			'last_id' => null,
		);
		echo json_encode($result);
	}
	/**
	 * ajax给衬衫加身型 衬衫清库存
	 */
	function addMsizedata(){
		$post = $_POST;

        if(C('match_qkc')){
        	$cid = $post['cid'];
        	$size = $post['size'];
            
            //验证
            $isok = false;
			$cartProductList = CartModel::get_cart_product_list();
	    	foreach ($cartProductList['productList'] as $key => $cart) {
                if($cart['id'] == $cid) $isok = true;
	    	} 
	    	if($isok){
				//选尺码购物
				$msizedata = array(4=>$size);
				$mid = MeasureModel::add_msizedata($msizedata);
				$addMdata['measure_id'] = $mid;
				D('cart_products')->where('id='.$cid)->save($addMdata);
				$result = array(
					'error' => 0,
					'message' => '',
					'last_id' => $cid,
				);
				echo json_encode($result);	exit;
	    	}       				
        }

		$result = array(
			'error' => 1,
			'message' => L('_OPERATION_FAIL_'),
			'last_id' => null,
		);
		echo json_encode($result);		
	}

	/**
	 * 批量加入购物车
	 *
	 */
	public function add_batch(){
        if(!unserialize(base64_decode(cookie('3dproduct_china')))){
            echo json_encode(array('status'=>0,'msg'=>'您当前没有搭配商品'));exit;
        }
        //处理数据
        $add_time=time();
        $pidArr = unserialize(base64_decode(cookie('3dproduct_china')));
        //加如购物车之前 判断商品是否有鞋子
        foreach ($pidArr as $pid) {
            $productInfo=ProductModel::get_product_info($pid);
            if($productInfo['model_id']==25&&(!$_REQUEST['foot_length']||!$_REQUEST['foot_width']||!$_REQUEST['size'])){
                //鞋子的尺码
                $shoe_size=ProductModel::get_shoes_size_data($productInfo['shoes_size_max'],$productInfo['shoes_size_min'],$productInfo['shoes_size_del']);
                echo json_encode(array('status'=>2,"msg"=>'请输选择您的鞋子尺码以及尺寸',"shoe_size"=>$shoe_size));exit;
            }
        }
        foreach ($pidArr as $pid) {
            $pid = intval($pid);
        	$productInfo = ProductModel::get_product_info($pid);
        	//产品不存在
			if(!$productInfo){
				continue;
			}
	        //下架商品
	        if($productInfo['display'] == 0){
                continue;
	        }
	        //配件直接加入购物车
	        if($productInfo['attribute_type']==1){
	        	$last_id=$this->add_product_cart($pid, 1, '', true,0,0,0,0,null,true,$add_time);
	        }else{
		        $attrData = '';
		        //读取定制商品的定制信息,同时放入缓存
		        list($attributeList, $size_type, $attrOptionArr) = CartModel::cart_attr_show($pid, $attrData, true);	          			        	
				$custom = unserialize(base64_decode(session('custom')));
				if(! isset($custom[$pid]) || empty($custom[$pid]) ){
					continue;
				}
				$attr = $custom[$pid];
                if($_REQUEST['size']){$attr['162']="162:Size::".$_REQUEST['size'];}
                if($_REQUEST['foot_length']){ $attr['159']="159:Foot Length::".$_REQUEST['foot_length'];}
                if($_REQUEST['foot_width']){$attr['160']="160:Foot Width::".$_REQUEST['foot_width'];}
	  	        $last_id=$this->add_product_cart($pid, 1, $attr, true, 2,0,0,0,null,true,$add_time);
	        }
        }
        if($last_id) {
            cookie('3dproduct_china', null);
        }
        $cartList = CartModel::get_cart_product_list();
        $count_cart=count($cartList['productList']);
        if(!unserialize(base64_decode(cookie('3dproduct_china')))&&$last_id){
            $status=1;
            $msg="加入购物车成功";
            if(intval($_REQUEST['action'])==1){
                $action=1;
            }else{
                $action=0;
            }
        }else{
            $status=0;
            $msg="加入购物车失败";
        }
        $respon=array('status'=>$status,'msg'=>$msg,'cart_count'=>$count_cart,'action'=>$action);
        echo json_encode($respon);
    }
}	